package org.todo.controller;

import java.beans.PropertyEditorSupport;
import org.todo.domain.Category;

/**
 * Custom property editor to display and store Category objects
 * @author Matthias Braunhofer
 */
public class CustomCategoryEditor extends PropertyEditorSupport {

    /**
     * Converts a Category object into a displayable text (i.e. its id)
     * @return
     */
    @Override
    public String getAsText() {
        Category category = (Category)getValue();
        if (category != null) {
            return String.valueOf(category.getId());
        }
        return null;
    }

    /**
     * Converts a displayable text (i.e. an id) into a Category object
     * @param text
     * @throws java.lang.IllegalArgumentException
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Category category = null;
        if (text != null) {
            int id = Integer.parseInt(text);
            category = new Category();
            category.setId(id);
        }
        setValue(category);
    } 
}
